package com.itheima.service.Impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.R;
import com.itheima.dao.OrderDao;
import com.itheima.execptiom.BusinessException;
import com.itheima.pojo.AddressBook;
import com.itheima.pojo.OrderDetail;
import com.itheima.pojo.Orders;
import com.itheima.pojo.ShoppingCart;
import com.itheima.service.IAddressBookService;
import com.itheima.service.IOrderDetailService;
import com.itheima.service.IOrderService;
import com.itheima.service.IShoppingCartService;
import com.itheima.utils.BaseContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderDao, Orders> implements IOrderService {

    @Autowired
    IShoppingCartService shoppingCartService;

    @Autowired
    IAddressBookService addressBookService;

    @Autowired
    IOrderDetailService orderDetailService;


    @Override
    public void  submit(Orders orders) {
        //1.获取当前是哪个用户下的单
        Long userId = BaseContext.getCurrentId();
        //2.查看购物车中的菜品和套餐
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);

        //判断购物车是否有订单
        if (shoppingCarts == null || shoppingCarts.size() == 0){
            throw new BusinessException("购物车为空,不能下单",0);
        }

        //IdWorker:生成全局唯一 ID 的
        long orderId = IdWorker.getId(); //订单号


        //3.组装订单明细
        //BigDecimal,用来对超过16位有效位的数进行精确的运算
        BigDecimal bigDecimal = new BigDecimal(0);
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();

            //工具类拷贝
            BeanUtils.copyProperties(shoppingCart,orderDetail,"amount");
            //设置订单号
            orderDetail.setOrderId(orderId);
            //金额 = 数量 * 单价
            BigDecimal number = new BigDecimal(shoppingCart.getNumber());
            BigDecimal price = shoppingCart.getAmount();
            orderDetail.setAmount(price.multiply(number));
            bigDecimal = price.multiply(number);
            //save订单明细
            orderDetailService.save(orderDetail);
        }

        //4,组装订单数据
        //查出它的默认地址
        LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        addressBookLambdaQueryWrapper.eq(AddressBook::getUserId,userId);
        addressBookLambdaQueryWrapper.eq(AddressBook::getIsDefault,1);
        AddressBook addressBook = addressBookService.getOne(addressBookLambdaQueryWrapper);
        if (addressBook == null){
            throw new BusinessException("请选中默认地址",0);
        }

        orders.setId(orderId);
        orders.setNumber(String.valueOf(orderId));//订单号
        orders.setStatus(4);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setPayMethod(1);
        orders.setAmount(bigDecimal);
        orders.setPhone(addressBook.getPhone());
        orders.setUserName(addressBook.getConsignee());

        //地址拼接
        String provinceName = addressBook.getProvinceName();
        String cityName = addressBook.getCityName();
        String districtName = addressBook.getDistrictName();
        String detail = addressBook.getDetail();
        orders.setAddress((provinceName!=null? provinceName :"")
            + (cityName!=null? cityName :"")
            + (districtName!=null? districtName :"")
            + (detail!=null? detail :""));
        //保存到订单表
        this.save(orders);

        //清空该用户的购物车
        shoppingCartService.remove(wrapper);
    }

    @Override
    public Page page(Integer page, Integer pageSize, String number, String beginTime, String endTime) {
        Page Ipage = new Page(page,pageSize);

        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(number != null,Orders::getNumber,number);
        wrapper.between(beginTime != null && endTime != null, Orders::getCheckoutTime,beginTime,endTime);
        Page date = this.page(Ipage, wrapper);

        //设置用户名
        return date;
    }

}
